//
//  NewFriendVC.swift
//  YueChat
//
//  Created by IMac on 2024/9/21.
//

import UIKit

class NewFriendVC: BaseVC {

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = KLocalizedString("NewFriend") //新朋友
        
        tableView.register(UINib(nibName: "NewFriendCell", bundle: nil), forCellReuseIdentifier: "NewFriendCell")
        InfoManager.shared.tabbar!.hideMarkIndex(1)
//        DMCCIMService.getInstance().zeroUnreadRequest()
        gosnFriend.delAddFreiendCount()
        getData()
    }

    @objc override func getData() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.tableView.mj_header?.endRefreshing()
        }

        let array = removeData(from: gosnRequest.listRequestReceive())
        dataSource = array
        tableView.reloadData()
        
        if dataSource.isEmpty {
            self.view.insertSubview(self.nullView, aboveSubview: self.view)
        } else {
            self.nullView.removeFromSuperview()
        }
        
    }

    func removeData(from array: [DMCCRequest]) -> [DMCCRequest] {
        var newList: [DMCCRequest] = []
        for req in array {
            if !req.group.isEmpty {
                removeData(withGroup: &newList, request: req)
            } else {
                removeData(withUser: &newList, request: req)
            }
        }
        return newList
    }

    private func removeData(withUser list: inout [DMCCRequest], request: DMCCRequest) {
        if let index = list.firstIndex(where: { $0.from == request.from }) {
            if list[index].timestamp < request.timestamp {
                list.remove(at: index)
                list.append(request)
            }
        } else {
            list.append(request)
        }
    }

    private func removeData(withGroup list: inout [DMCCRequest], request: DMCCRequest) {
        if let index = list.firstIndex(where: { $0.from == request.from && $0.group == request.group }) {
            if list[index].timestamp < request.timestamp {
                list.remove(at: index)
                list.append(request)
            }
        } else {
            list.append(request)
        }
    }

    // UITableViewDataSource Methods
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   
        let cell = tableView.dequeueReusableCell(withIdentifier: "NewFriendCell", for: indexPath) as! NewFriendCell
        cell.setInfo(info: dataSource[indexPath.row] as! DMCCRequest)
        cell.block = {
            self.addFriend(indexPath.row)
        }
        return cell
    }

    func addFriend(_ index: Int) {
        let request = dataSource[index] as! DMCCRequest
        if request.type == OsnRequestType.Friend {
            MHAlert.showLoading()
            
            Task {
                let res = await gosnRequest.acceptFriend(request)
                await MainActor.run {
                    if res {
                        MHAlert.showMessage(KLocalizedString("AlertAddSuccess"))
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: kDeleteUserChanged), object: nil, userInfo: nil)
                        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                            self.getData()
                        }
                    }else{
                        MHAlert.showMessage(KLocalizedString("AlertAddFail"))
                    }
                }
            }
            
        } else {
            MHAlert.showLoading()
            
            Task {
                let res = await gosnRequest.acceptMember(request)
                await MainActor.run {
                    if res {
                        MHAlert.showMessage(KLocalizedString("GroupMessageBeenSended"))
                        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                            self.getData()
                        }
                    }else{
                        MHAlert.showMessage(KLocalizedString("GroupMessageTimeOut"))
                    }
                }
            }
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let info = dataSource[indexPath.row] as! DMCCRequest
        let userInfo = gosnUser.getUserInfoDefault(info.from)
        if gosnFriend.isFriend(userInfo.userId) {
            let vc = UserDetailVC(userInfo: userInfo)
            navigationController?.pushViewController(vc, animated: true)
        } else {
            let vc = AddUserVC(userInfo: userInfo)
            navigationController?.pushViewController(vc, animated: true)
        }
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 85
    }

}
